<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Comments;
use App\Http\Resources\Orders;
use App\Models\Comment;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CommentController extends Controller
{
    /**
     * 评论列表
     */
    public function index(Request $request)
    {
        $data = $request->all([
            'page', 'limit',
            'filter', # 0 全部 1 最新 2 好评 3 差评 4 有图
            'product_id',
        ]);

        return Api::success(Comments::collection(Comment::where('product_id', (int)$data['product_id'])->filter($data)->get()));
    }

    /**
     * 添加评论
     */
    public function store(Request $request)
    {
        $data = $request->all([
            "order_id",
            "item_id",
            "content",
            "score",
            "level",
            "images",
        ]);
        DB::beginTransaction();

        $images = json_decode($data['images'], true);

        /** @var Order $order */
        $order = Order::where('id', $data['order_id'])->first();

        $orderItem = OrderItem::query()->find($data['item_id']);

        if (!$order) {
            return Api::failure(404, '订单未找到');
        }

        if (!$order->getHint()->canComment()) {
            return Api::failure(403, '该订单不允许评论');
        }

        if (!$orderItem) {
            return Api::failure(404, '商品未找到');
        }

        if ($orderItem->reviewed_at) {
            return Api::failure(402, '商品已评价！');
        }

        try {
            $orderItem->comment($data, $images);

            // 所有商品都评价完, 修改订单状态
            if ($order->items()->whereNull('reviewed_at')->get()->isEmpty()) {
                $order->done();
            }

            // 添加商品评论数
            Product::query()->find($orderItem->product_id)->increment('count_comments');
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return Api::failure(500, '商品评价失败! ');
        }

        return Api::success($order->display());
    }

    /**
     * 删除评论
     */
    public function delete(Request $request)
    {
        $comment = Comment::query()->find($request->input('id'));

        Product::query()->find($comment->product_id)->decrement('count_comments');

        $comment->delete();

        return Api::success();
    }
}
